package game.view;

import game.*;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 * Score board UI - user interface for score board.
 * @author Natchanon Hongladaromp
 *
 */
public class ScoreBoardUI extends JFrame implements Observer
{
	private JTextField textField;
	private JScrollPane scrollPane;
	private JTable table;
	private DefaultTableModel model;
	private ScoreBoard board;
	
	/**
	 * Construct of this ui.
	 * @param board
	 */
	public ScoreBoardUI(ScoreBoard board) {
		this.board = board;
		initComponents();
	}
	
	/**
	 * Sets board.
	 * @param board board
	 */
	public void setBoard(ScoreBoard board)
	{
		this.board = board;
	}

	/**
	 * Initial components.
	 */
	private void initComponents()
	{
		JPanel p = new JPanel();
		p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
		
		JPanel p1 = new JPanel();		
		model = new DefaultTableModel();
		table = new JTable(model);
		scrollPane = new JScrollPane(table);
		textField = new JTextField();
		model.addColumn("Name");
		model.addColumn("Score");
		p1.add(textField);
		p1.add(scrollPane);
		table.setEnabled(false);
		
		JPanel p2 = new JPanel();
		p2.setLayout(new FlowLayout());
		JButton button = new JButton("Reset");
		button.addActionListener(new ActionListener()
		{
			
			@Override
			public void actionPerformed(ActionEvent arg0)
			{
				board.reset();
			}
		});
		p2.add(button);
		
		p.add(p1);
		p.add(p2);
		
		add(p);
	}

	@Override
	public void update(Observable arg0, Object arg1)
	{
		if(arg1 == UpdateType.UPDATE_SCORE)
		{
			while(model.getRowCount()>0)
				model.removeRow(0);
			for(ScoreItem i: board.getScore())
			{
				model.addRow(new Object[]{i.getName(),String.format("%.2f", i.getScore())});
			}
		}
	}
	
	/**
	 * Runs method.
	 */
	public void run()
	{
		pack();
		setVisible(true);
	}
}
